package com.jied.duodian.service.Impl;

import com.jied.duodian.dao.DdShoppingDAO;
import com.jied.duodian.entity.DdShopping;
import com.jied.duodian.entity.DdShoppingExample;
import com.jied.duodian.service.DdShoppingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description:
 *
 * @author LiJie
 * @date Created on 2020/11/5
 * WWW https://github.com/j6l
 */
@Service
@Slf4j
@Transactional
public class DdShoppingServiceImpl implements DdShoppingService {

    @Autowired
    DdShoppingDAO ddShoppingDAO;

    @Override
    public Integer addshopping(DdShopping shopping) {
        if (panduan( shopping )) {
            addshoppingByid( shopping );
            return 1;
        } else
            return ddShoppingDAO.insertSelective( shopping );
    }

    @Override
    public Integer jianshopping(DdShopping shopping) {
        DdShopping shopping1 = getDdShoppings( shopping ).get( 0 );
        shopping1.setProductNum( shopping1.getProductNum() - 1 );
        if (shopping1.getProductNum() < 1)
            return delshoppding( shopping1 );
        return ddShoppingDAO.updateByPrimaryKeySelective( shopping1 );
    }

    @Override
    public Integer delshoppding(DdShopping shopping) {
        DdShopping shopping1 = getDdShoppings( shopping ).get( 0 );
        return ddShoppingDAO.deleteByPrimaryKey( shopping1.getId() );
    }

    @Override
    public List<DdShopping> getshoppingBuuserid(Integer id) {
        DdShoppingExample example = new DdShoppingExample();
        DdShoppingExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo( id );
        return ddShoppingDAO.selectByExample( example );
    }

    @Override
    @Cacheable(cacheNames = "qt", keyGenerator = "keyGenerator")
    public DdShopping getshoppingByid(Integer id) {
        return ddShoppingDAO.selectByPrimaryKey( id );
    }

    public Boolean panduan(DdShopping shopping) {
        List<DdShopping> list = getDdShoppings( shopping );
        return list.size() == 0 ? false : true;
    }

    @Override
    public Integer addshoppingByid(DdShopping shopping) {
        DdShopping shopping1 = getDdShoppings( shopping ).get( 0 );
        shopping1.setProductNum( shopping1.getProductNum() + 1 );
        return ddShoppingDAO.updateByPrimaryKeySelective( shopping1 );
    }

    public List<DdShopping> getDdShoppings(DdShopping shopping) {
        DdShoppingExample example = new DdShoppingExample();
        DdShoppingExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo( shopping.getUserId() );
        criteria.andProductIdEqualTo( shopping.getProductId() );
        List<DdShopping> list = ddShoppingDAO.selectByExample( example );
        return list;
    }
}
